<template>
  <ele-page>
    <!-- 搜索表单 -->
    <search @search="reload" :where="defaultWhere" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        highlight-current-row
        row-key="id"
        row-click-checked
        border
        stripe
        :where="defaultWhere"
        :loadOnCreated="false"
      >
        <template #realname="{ row }">
          <span class="pointer blue" @click="showStudentDetail(row)">
            {{ row.realname }}
          </span>
        </template>
        <template #salaryAgency="{ row }">
          <el-tag type="info" v-if="row.salary_agency_id == 0">未签约</el-tag>
          <span v-else>{{ row.salaryAgency }}</span>
        </template>
        <template #lastTax="{ row }">
          <span class="pointer blue" @click="openTax(row)">
            {{ row.lastTax }}
          </span>
        </template>
        <template #status="{ row }">
          <span v-if="row.status === 9999"></span>
          <div v-else>
            <el-tag
              v-if="row.wechat_res_code_des !== '' && row.status === 2"
              type="warning"
              >打款失败</el-tag
            >
            <el-tag
              v-else
              :type="statusFilter(row.status)"
              class="pointer"
              @click="handleState(row.id, row.username, row.status)"
            >
              {{ statusText(row.status) }}
            </el-tag>
          </div>
        </template>
        <template #identity="{ row }">
          <span :class="identityClass(row.identity)">
            {{ identityText(row.identity) }}
          </span>
        </template>
        <template #pay_type="{ row }">
          <span v-if="row.pay_type === '银行卡'">{{
            row.pay_account_info
          }}</span>
          <span v-else>{{ row.pay_type }}</span>
        </template>
        <template #pay_account="{ row }">
          <span>{{ row.pay_account }}</span>
        </template>
        <template #toolbar="{}">
          <el-button
            type="success"
            @click="setStatus(null, 1)"
            :icon="DocumentCopy"
          >
            批量通过
          </el-button>
          <el-button type="" @click="exportExcel" :icon="DocumentCopy">
            导出表格
          </el-button>
        </template>

        <template #action="{ row }">
          <span v-if="row.status === 9999">/</span>
          <el-button-group v-else>
            <el-button
              type="primary"
              size="small"
              @click="openBalanceDetail(row)"
              >钱包明细</el-button
            >
            <el-button
              v-if="row.status === 0"
              type="success"
              size="small"
              @click="setStatus(row, 1)"
              >已处理</el-button
            >
            <el-button
              v-if="row.status === 0"
              type="danger"
              size="small"
              @click="setStatus(row, 2)"
            >
              未通过
            </el-button>
          </el-button-group>
        </template>
      </ele-pro-table>
    </ele-card>

    <!-- 处理结果提示页面 -->
    <ele-modal :width="600" title="处理结果" v-model="visible">
      <div v-for="item in warningText" :key="item">{{ item }}</div>
    </ele-modal>
    <!-- 处理结果提示页面 -->

    <!-- 学生详情 -->
    <detail
      v-model="showDetail"
      :student-id="currentId"
      @done="reloadCurrentPage"
      @close="reloadCurrentPage"
    />
    <!-- 资产详情 -->
    <assetc v-model="showAssetc" :user-id="currentId" :type="0" />
    <Tax
      v-model="showTax"
      :data="current"
      :student-id="currentId"
      @close="reloadCurrentPage"
      @done="reloadCurrentPage"
    />
  </ele-page>
</template>

<script setup>
  import { ref, computed } from 'vue';
  import Search from './search.vue';
  import { DocumentCopy } from '@element-plus/icons-vue';
  import Detail from '@/views/student/components/detail.vue';
  import Assetc from '@/views/student/components/assetc-detail.vue';
  import { pageWithdraw, exportWithdrawList, payWithdraw } from '@/api/money';
  import { EleMessage } from 'ele-admin-plus/es';
  import { ElMessageBox } from 'element-plus/es';
  import Tax from '@/views/student/tax/index.vue';

  const props = defineProps({
    defaultWhere: {
      type: Object,
      default: () => {}
    },
    action: {
      type: String,
      default: 'list'
    }
  });
  /** 表格实例 */
  const tableRef = ref(null);

  const identityText = (value) => {
    const cs = {
      1: '在校',
      2: '毕业'
    };
    return cs[value];
  };
  const identityClass = (state) => {
    const stateMap = {
      1: 'orange',
      2: ''
    };
    return stateMap[state];
  };

  /** 表格列配置 */
  const columns = computed(() => {
    const cols = [];

    cols.push({
      type: 'selection',
      columnKey: 'selection',
      width: 50,
      align: 'center',
      fixed: 'left',
      selectable: (row) => {
        return row.status !== 9999 && status.value === 0;
      }
    });

    cols.push(
      {
        prop: 'id',
        label: '编号',
        width: 85,
        align: 'center'
      },
      {
        prop: 'tenant',
        label: '所属公司',
        width: 100
      },
      {
        slot: 'status',
        label: '状态',
        align: 'center',
        width: 85
      }
    );
    if (
      status.value === 0 &&
      (payType.value == '支付宝' || payType.value == '微信')
    ) {
      cols.push({
        label: '自动到账失败原因',
        prop: 'wechat_res_code_des',
        width: 180
      });
    }
    if (status.value === 2) {
      cols.push({
        label: '失败原因',
        prop: 'wechat_res_code_des',
        width: 180
      });
    }
    cols.push(
      {
        slot: 'realname',
        label: '姓名',
        width: 80
      },
      {
        slot: 'salaryAgency',
        label: '零工平台',
        width: 100
      },
      {
        label: '手机号',
        prop: 'tel',
        width: 120
      },
      {
        width: 170,
        slot: 'lastTax',
        label: '个税记录'
      },
      {
        slot: 'pay_type',
        label: '提现类型',
        width: 120
      },
      {
        slot: 'pay_account',
        label: '收款账号'
      },
      {
        prop: 'pay_account_name',
        label: '账号姓名',
        width: 120
      },
      {
        prop: 'amount',
        label: '金额',
        width: 90
      },
      {
        prop: 'create_time',
        label: '申请时间',
        width: 159
      },
      {
        prop: 'paid_user',
        label: '处理人',
        width: 100
      },
      {
        prop: 'paid_time',
        label: '处理时间',
        width: 159
      }
    );
    // if (status.value == 1) {
    //   cols.push({
    //     prop: 'paid_type',
    //     label: '付款方式',
    //     width: 85
    //   });
    // }
    cols.push({
      columnKey: 'action',
      label: '操作',
      slot: 'action',
      width: 230,
      fixed: 'right'
    });
    return cols;
  });

  /** 表格选中数据 */
  const selections = ref([]);

  /** 当前编辑数据 */
  const currentId = ref(null);

  /** 是否显示编辑弹窗 */
  const showDetail = ref(false);
  /** 是否显示编辑弹窗 */
  const showAssetc = ref(false);

  /** 打开编辑弹窗 */
  const showTax = ref(false);
  const openTax = (row) => {
    current.value = row ?? null;
    currentId.value = row.student_id;
    showTax.value = true;
  };

  const statusText = (value) => {
    const cs = {
      9: '未通过',
      2: '未通过',
      1: '已处理',
      0: '待审核'
    };
    return cs[value];
  };
  const statusFilter = (status) => {
    const statusMap = {
      9: '',
      2: 'danger',
      1: 'success',
      0: 'info'
    };
    return statusMap[status];
  };

  const datasource = ({ page, limit, where, orders }) => {
    return pageWithdraw({
      ...where,
      ...orders,
      page,
      limit
    });
  };
  /** 导出表格 */
  const exportExcel = () => {
    const loading = EleMessage.loading('请求中..');
    tableRef.value?.fetch(({ where }) => {
      // 方法的参数与数据源的完全一致
      // 请求查询全部接口
      console.log(where);
      var requestData = where;
      requestData.limit = 99999999;
      requestData.page = 1;

      exportWithdrawList(requestData)
        .then((res) => {
          loading.close();
          window.open(res);
        })
        .catch(() => {
          loading.close();
        });
    });
  };

  const status = ref(0);

  const payType = ref('');
  /** 搜索 */
  const reload = (where) => {
    status.value = where ? where.status : 0;
    payType.value = where ? where.pay_type : '';
    console.log(status.value === 0, '一天到晚出错');
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  const reloadCurrentPage = (where, page) => {
    tableRef.value?.reload?.({ page, where });
  };
  /** 打开编辑弹窗 */
  const showStudentDetail = (row) => {
    currentId.value = row.student_id ?? 0;
    showDetail.value = true;
  };

  /** 打开编辑弹窗 */
  const openBalanceDetail = (row) => {
    currentId.value = row.student_id ?? 0;
    showAssetc.value = true;
  };

  const current = ref([]);

  // 审核
  const setStatus = (row, status = 1) => {
    const action = ['拒绝', '通过', '拒绝'];
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
      EleMessage.error('请至少选择一条数据');
      return;
    }
    let rowsCount = rows.length;
    ElMessageBox.confirm(
      '确定要' +
        action[status] +
        '“' +
        rows.map((d) => d.realname).join(', ') +
        '”共' +
        rowsCount +
        '人的提现申请吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        const loading = EleMessage.loading('请求中..');
        var ids = [];
        for (let i = 0; i < rows.length; i++) {
          const v = rows[i];
          ids.push(v['id']);
        }
        var requestData = {
          paid_type: '', // 这里只是提交微信和支付宝的申请，所以paid_type直接为空即可
          status: status,
          ids: JSON.stringify(ids)
        };
        payWithdraw(requestData)
          .then((res) => {
            loading.close();
            if (res === '处理成功') {
              EleMessage.success(res);
            } else {
              warningText.value = res;
              showRes();
            }
            reload();
          })
          .catch((e) => {
            loading.close();
            EleMessage.error(e.message);
          });
      })
      .catch(() => {});
  };

  /** 处理结果显示 */
  const visible = ref(false);
  const warningText = ref([]);
  const showRes = () => {
    visible.value = true;
  };
</script>

<script>
  export default {
    name: 'SystemUser'
  };
</script>
